import {Component, OnInit, EventEmitter, Output, Input} from '@angular/core';

@Component({
    selector: 'common-page',
    template: `
        <!--分页-->
        <div class="pagediv">
            共{{total}}条记录，
            每页
            <select [(ngModel)] = "pagesize" (change)="changePageSize()">
			  <option *ngFor="let val of pagesizeArray" [value]="val">{{val}}</option>
			</select>

            
            条
            
            <span>{{getCurrent()}}/{{getPageCount()}}</span>
            <a href="javascript:;" (click)="first()">首页</a>
            <a href="javascript:;" (click)="prev()">上页</a>
            <a href="javascript:;" (click)="next()">下页</a>
            <a href="javascript:;" (click)="end()">末页</a>
        </div>
    `
})
export class PageComponent implements OnInit{
	/** current 当前页码 */
    @Input() current: number | string;
    
    /** 总数 */
    @Input() total: number | string;
    
    /** 每页 显示条数*/
    @Input() pagesize: number | string;
   
    @Output() pagesizeChange = new EventEmitter<number>();
    
    @Output() pageChange = new EventEmitter<number>();
    
    /**页码长度 */
    private pagesLength: number = 7;
    
    private pagesizeArray = [10, 50, 100];
    
    
    constructor() { 
        
    }
    
    ngOnInit() { 
   
    }
    
    /** 获取当前页数 */
    getCurrent(){
    	if(this.getPageCount() < this.current){
    		this.current = this.getPageCount();
    	}
        return this.current;
    }
    
    
    /** 总共有多少页 */
    getPageCount(){
        return Math.ceil(+this.total/+this.pagesize);
    }
   
    /** 每页显示的数量发生变化 **/
    changePageSize(){
    	this.pageChange.emit(1);
    	this.pagesizeChange.next(+this.pagesize);
    	
    }
    
    next(){
        console.log('点击了 下一页');
        
        if(this.current == this.getPageCount()){
        	return;
        }
        
        if(this.current < this.getPageCount()){
        	this.current = +this.current + 1;
        }
        
        this.pageChange.emit(+this.current);
    }
    
    prev(){
        console.log('点击了 上一页');
        
        if(this.current == 1){
            return;
        }
        
        if(this.current > 1){
            this.current = +this.current - 1;
        }
        
        this.pageChange.emit(+this.current);
    }
    
    first(){
    	console.log('点击了首页');
    	
    	if(this.current == 1){
    		return;
    	}
    	
    	this.current = 1;
    	
    	this.pageChange.emit(+this.current);
    }
    
    end(){
        console.log('点击了末页');
        
        if(this.current == this.getPageCount()){
            return;
        }
        
        this.current = this.getPageCount();
        
        this.pageChange.emit(+this.current);
    }
}